<?php

/**
 * 后台菜单管理类
 *
 * @author 张志豪
 */

namespace Think\Modules\Admin;

class Menu
{

	/**
	 * 获取所有菜单或用户有权限的所有菜单
	 *
	 * @param mixed $auth 注：auth是以菜单KEY为键名的数组，键值不作要求
	 * @return array
	 */
	static public function getAllMenu($auth = false)
	{
		$Menu = M("adminmeu");
		$data = $Menu->where(['parentid' => 0])->order('displayorder DESC')->select();
		empty($data) && $first = [];
		$return = [];
		foreach ($data as $v)
		{
			$id = $v['id'];
			if (isset($auth[$v['key']]) || !$auth)
			{
				$return[$id] = $v;
				$return[$id]['child'] = self::getMenuChild($id, $auth);
				foreach ($return[$id]['child'] as $key => $value)
				{
					$cid = $value['id'];
					$return[$id]['child'][$key]['child'] = self::getMenuChild($cid, $auth);
				}
			}
		}
		return $return;
	}

	/*
	 * 获取菜单的下级子菜单，如果传递auth，则只返回auth中存在的菜单
	 *
	 * @param int id 菜单ID
	 * @param mixed auth  注：auth是以菜单KEY为键名的数组，键值不作要求
	 * @return array
	 */
	static public function getMenuChild($id, $auth = false)
	{
		$Menu = M("adminmeu");
		$data = $Menu->where(['parentid' => $id])->order('displayorder DESC')->select();
		if ($auth)
		{
			foreach ($data as $k => $v)
			{
				if (!isset($auth[$v['key']]))
				{
					unset($data[$k]);
				}
			}
		}
		return empty($data) ? [] : $data;
	}

	/**
	 * 根据菜单KEY返回菜单
	 *
	 * @param string $key  菜单KEY
	 * @return array
	 */
	static public function getMenuByKey($key)
	{
		$db = Bridge::pdo(Bridge::DB_ADMIN_R);
		$data = $db->query("select * from AdminMenu where `key`='{$key}'")->fetch();
		empty($data) && $data = [];
		return $data;
	}
}